package com.rainwood.material.ui;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.android.zxing.android.QRCodeCaptureActivity;
import com.bigkoo.pickerview.configure.PickerOptions;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.rainwood.material.R;
import com.rainwood.material.adapter.CheckOutAdapter;
import com.rainwood.material.base.BaseActivity;
import com.rainwood.material.bean.DeptBean;
import com.rainwood.material.bean.MarterialDetial;
import com.rainwood.material.net.NetBean;
import com.rainwood.material.uitls.LoggerUtils;
import com.rainwood.material.uitls.PermissionUtil;
import com.rainwood.material.uitls.ToastUtils;
import com.rainwood.material.view.dialog.CommonDialog;
import com.rainwood.material.view.titlebar.OnTitleBarListener;
import com.rainwood.material.view.titlebar.TitleBar;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @auther : hhx
 * @date :  2021/3/4
 * @des :
 */
public class CheckOutActivity extends BaseActivity {


    private static final int REQUEST_SCAN_CODE = 0x1111;
    private static final int PERMISSRESULT = 0x1112;
    private TitleBar titleBar;
    private AppCompatTextView tvScan;
    private View viewLine;
    private LinearLayout llFitter;
    private AppCompatTextView tvDept;
    private AppCompatTextView tvUserName;
    private AppCompatTextView tvAll;
    private View viewLineBottom;
    private SwipeRefreshLayout swFresh;
    private RecyclerView rvList;
    private TextView tvEmpty;
    private List<DeptBean> deptBeans;
    private int deptOp;
    private String deptName;
    private int userOp;
    private String userName;
    private String deptId = "";
    private String userId = "";
    private CheckOutAdapter checkOutAdapter;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_check_out;
    }

    @Override
    protected void initView() {

        titleBar = (TitleBar) findViewById(R.id.title_bar);
        tvScan = (AppCompatTextView) findViewById(R.id.tv_scan);
        viewLine = (View) findViewById(R.id.view_line);
        llFitter = (LinearLayout) findViewById(R.id.ll_fitter);
        tvDept = (AppCompatTextView) findViewById(R.id.tv_dept);
        tvUserName = (AppCompatTextView) findViewById(R.id.tv_user_name);
        tvAll = (AppCompatTextView) findViewById(R.id.tv_all);
        viewLineBottom = (View) findViewById(R.id.view_line_bottom);
        swFresh = (SwipeRefreshLayout) findViewById(R.id.sw_fresh);
        rvList = (RecyclerView) findViewById(R.id.rv_list);


        tvEmpty = (TextView) findViewById(R.id.tv_empty);


        titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) {
                finish();
            }

            @Override
            public void onTitleClick(View v) {

            }

            @Override
            public void onRightClick(View v) {

            }
        });

        tvScan.setOnClickListener(view -> {
            checkCameraPermission();
        });

        tvDept.setOnClickListener(view -> {
            showDeptPicker();
        });

        tvUserName.setOnClickListener(view -> showNamePicker());

        tvAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvDept.setText("科室");
                tvUserName.setText("用户名");
                userId = "";
                deptId = "";
                deptName = "";
                userName = "";
                getOutList("", "");
            }
        });

        swFresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getOutList(deptId, userId);
            }
        });

    }

    private void showNamePicker() {
        if (deptBeans == null || deptBeans.isEmpty()) {
            return;
        }
        if (TextUtils.isEmpty(deptName)) {
            ToastUtils.show("请选择科室");
            return;
        }
        List<String> users = new ArrayList<>();
        for (int i = 0; i < deptBeans.size(); i++) {
            if (deptName.equals(deptBeans.get(i).getDepartmentName())) {
                users.add(deptBeans.get(i).getName());
            }
        }
        PickerOptions pickerOptions = new PickerOptions(PickerOptions.TYPE_PICKER_OPTIONS);
        pickerOptions.context = this;
        pickerOptions.optionsSelectListener = new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                userOp = options1;
                userName = users.get(options1);
                tvUserName.setText(userName);

                for (int i = 0; i < deptBeans.size(); i++) {
                    if (userName.equals(deptBeans.get(i).getName())) {
                        userId = deptBeans.get(i).getStid();
                    }
                }
                getOutList(deptId, userId);

            }
        };
        OptionsPickerView optionsPickerView = new OptionsPickerView(pickerOptions);
        optionsPickerView.setPicker(users);
        optionsPickerView.setSelectOptions(userOp);
        optionsPickerView.show();

    }


    private void showDeptPicker() {
        if (deptBeans == null || deptBeans.isEmpty()) {
            return;
        }
        List<String> depts = new ArrayList<>();
        for (int i = 0; i < deptBeans.size(); i++) {
            if (depts.contains(deptBeans.get(i).getDepartmentName())) continue;
            depts.add(deptBeans.get(i).getDepartmentName());
        }


        PickerOptions pickerOptions = new PickerOptions(PickerOptions.TYPE_PICKER_OPTIONS);
        pickerOptions.context = this;
        pickerOptions.optionsSelectListener = new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                if (deptOp != options1) {
                    userOp = 0;
                    tvUserName.setText("");
                }
                userOp = 0;
                deptOp = options1;
                deptName = depts.get(options1);
                tvDept.setText(deptName);
                for (int i = 0; i < deptBeans.size(); i++) {
                    if (deptName.equals(deptBeans.get(i).getDepartmentName())) {
                        deptId = deptBeans.get(i).getDepartmentId();
                        break;
                    }
                }
                getOutList(deptId, userId);
            }
        };
        OptionsPickerView optionsPickerView = new OptionsPickerView(pickerOptions);
        optionsPickerView.setPicker(depts);
        optionsPickerView.setSelectOptions(deptOp);
        optionsPickerView.show();

    }

    private void checkCameraPermission() {
        if (!PermissionUtil.hasPermission(this, PermissionUtil.CAMERA)) {
            PermissionUtil.requestPermission(this, PermissionUtil.CAMERA, PermissionUtil.REQUEST_CAMERA);
        } else {
            turnToScanPage();
        }
    }

    private void turnToScanPage() {
        Intent intent = new Intent(this, QRCodeCaptureActivity.class);
        intent.putExtra(QRCodeCaptureActivity.STATUS_BAR_COLOR, Color.parseColor("#99000000"));
        startActivityForResult(intent, REQUEST_SCAN_CODE);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case PermissionUtil.REQUEST_CAMERA:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    turnToScanPage();
                } else {
                    //shouldShowRequestPermissionRationale 拒绝时是否勾选了不再提示
                    // 没有勾选返回true ,勾选不再提醒返回false
                    boolean hasAlwaysDeniedPermission = !ActivityCompat.shouldShowRequestPermissionRationale(this, PermissionUtil.STORAGE[0]);
                    //勾选不再提醒,会过滤系统的对话框，这时需要手动去设置权限
                    if (hasAlwaysDeniedPermission) {
                        handlePermission();
                    }
                }
                break;

            default:
                break;
        }

    }

    private void handlePermission() {

        final CommonDialog dialog = new CommonDialog(this);
        dialog.setMessage("应用需要访问读取权限，不授权将无法正常工作！")
                .setImageResId(R.mipmap.icon_app)
                .setTitle("系统提示")
                .setSingle(true).setOnClickBottomListener(new CommonDialog.OnClickBottomListener() {
            @Override
            public void onPositiveClick() {
                dialog.dismiss();
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                Uri uri = Uri.fromParts("package", getPackageName(), null);
                intent.setData(uri);
                startActivityForResult(intent, PermissionUtil.REQUEST_CAMERA);
                dialog.dismiss();
            }

            @Override
            public void onNegtiveClick() {
                dialog.dismiss();
            }
        }).show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //test


        if (requestCode == REQUEST_SCAN_CODE && resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            String result = null;
            if (bundle != null) {
                result = bundle.getString(QRCodeCaptureActivity.CODE_CONTENT);
                LoggerUtils.d("扫码", "-------- result-------- " + result);
                turnToOutDetailPage(result);
            }

        }

    }

    private void turnToOutDetailPage(String result) {
        Intent intent = new Intent(this, CheckOutDetailActivity.class);
        intent.putExtra("code", result);
        startActivity(intent);
    }

    @Override
    protected void initData() {
        getOutList(deptId, userId);
        getDeptList();
    }

    private void getDeptList() {
        Map<String, Object> map = new HashMap<>(1);
        addPostRequest(NetBean.DEPTUSERLIST, map);
    }

    private void getOutList(String deptId, String userId) {
        Map<String, Object> map = new HashMap<>(1);
        map.put("departmentId", deptId);
        map.put("stid", userId);
        map.put("page", 1);
        map.put("offset", 10);
        addPostRequest(NetBean.OUTLIST, map);
    }

    @Override
    public void onSuccess(String res, int tag) {
        if (tag == NetBean.OUTLIST.getTag()) {
            swFresh.setRefreshing(false);
            List<MarterialDetial> marterialDetials = JSON.parseArray(res, MarterialDetial.class);
            if (marterialDetials != null && !marterialDetials.isEmpty()) {
                fillRvList(marterialDetials);
            } else {
                showEmpty();
            }
        } else if (tag == NetBean.DEPTUSERLIST.getTag()) {
            JSONObject jsonObject = JSON.parseObject(res);
            deptBeans = JSON.parseArray(jsonObject.getString("department"), DeptBean.class);
        }

    }

    @Override
    public void onFail(String res, int tag) {
        if (tag == NetBean.OUTLIST.getTag()) {
            showEmpty();
        }
    }

    private void fillRvList(List<MarterialDetial> marterialDetials) {
        swFresh.setVisibility(View.VISIBLE);
        tvEmpty.setVisibility(View.GONE);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        rvList.setLayoutManager(layoutManager);
        DividerItemDecoration divider = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(this, R.drawable.custom_divider));
        int itemDecorationCount = rvList.getItemDecorationCount();
        if (itemDecorationCount != 0) {
            rvList.removeItemDecorationAt(0);
        }
        rvList.addItemDecoration(divider);

        checkOutAdapter = new CheckOutAdapter();
        checkOutAdapter.setMarterialDetials(marterialDetials);
        rvList.setAdapter(checkOutAdapter);

    }

    private void showEmpty() {
        swFresh.setVisibility(View.GONE);
        tvEmpty.setVisibility(View.VISIBLE);

    }

    @Override
    public void onError(String msg) {


    }
}
